package org.come.Jpanel;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import org.come.bean.LoginResult;
import org.come.bean.ShopGoodsBean;
import org.come.model.Shop;
import org.come.mouslisten.ShopFyMouslisten;
import org.come.mouslisten.ShopMouslisten;
import org.come.socket.Agreement;
import org.come.socket.SendMessageUntil;
import org.come.until.CutButtonImage;
import org.come.until.GoodsListFromServerUntil;
import org.come.until.Util;

import com.tool.btn.FormsOnOffBtn;
import com.tool.btn.ShoppingBuyBtn;
import com.tool.role.RoleData;
import com.tool.tcpimg.UIUtils;
import com.updateNew.MyIsif;



public class ShoppingBuyJpanel extends JPanel {
    private List<Shop> shops;// 商品列表
    private List<Shop> shopList; // 限购总商品列表

    // 翻页按钮
    private List<JLabel> pages;// 商品列表
    private int index = 0;// 判断是在第几页
    private Shop shop;// 当前要购买的物品
    private int xz = -1;// 当前要购买的物品位置

    private BigDecimal Unitprice,// 单价
            Totalsum;// 总价
    private JTextField textNumber;// 数量
    private ShoppingBuyBtn btnsurebuy,// 确认购买
            xianyuBtn,// 仙玉菜单按钮
            dahuabiBtn; // 大话币菜单按钮

    public JLabel[] GoodsListLabel = new JLabel[24];// 用来存放24个物品表格

    // 货币类型
    public String Currency = "金钱";
    private JLabel currencyLab; // 展示的货币类型
    // 总额
    public BigDecimal Balance;
    private ShopMouslisten[] shopMouslistens = new ShopMouslisten[24];
    // private int Flag = 0;
    private int count = 1;// 是否是限购
    private int goldType = 1;// 限购类型 1是仙玉 0是金钱
    private Integer nId; // 限购商人Id

    public ShoppingBuyJpanel() throws Exception {
    		this.setPreferredSize(new Dimension(378, 398));
	        this.setLayout(null);
	        this.setBackground(UIUtils.Color_BACK);

	        // 关闭按钮事件
	        FormsOnOffBtn offBtn = new FormsOnOffBtn("inkImg/old/2/1.png", 1, 23);
	        offBtn.setBounds(378 - 37, 10, 25, 25);
	        this.add(offBtn);

	        this.add(getXianyuBtn());
	        this.add(getDahuabiBtn());
	        this.add(getCurrencyLab());

	        Unitprice = new BigDecimal(0);
	        Totalsum = new BigDecimal(0);

	        // 数量
	        textNumber = new JTextField();
	        textNumber.setText("0");
	        textNumber.setBackground(UIUtils.Color_BACK);
	        textNumber.setBorder(BorderFactory.createEmptyBorder());
	        textNumber.setForeground(Color.white);
	        textNumber.setCaretColor(Color.white);
	        textNumber.setBounds(100, 297, 151, 16);
	        textNumber.getDocument().addDocumentListener(new DocumentListener() {
	            @Override
	            public void removeUpdate(DocumentEvent e) {
	                // TODO Auto-generated method stub
	                String s = textNumber.getText();
	                try {
	                    int sum = Integer.parseInt(s);
	                    long price = Long.parseLong(Unitprice.toString());
	                    // labTotalsum.setText(price*sum+"");
	                    Totalsum = new BigDecimal((price * sum));
	                } catch (NumberFormatException e1) {
	                    // TODO Auto-generated catch block
	                }
	            }

	            @Override
	            public void insertUpdate(DocumentEvent e) {
	                // TODO Auto-generated method stub
	                String s = textNumber.getText();
	                try {
	                    int sum = Integer.parseInt(s);
	                    long price = Long.parseLong(Unitprice.toString());
	                    // labTotalsum.setText(price*sum+"");
	                    Totalsum = new BigDecimal((price * sum));
	                } catch (NumberFormatException e1) {
	                    // TODO Auto-generated catch block
	                }

	            }

	            @Override
	            public void changedUpdate(DocumentEvent e) {
	                // TODO Auto-generated method stub
	            }
	        });
	        // 限制输入内容为数字切数字不大于100
	        textNumber.addKeyListener(new KeyListener() {
	            @Override
	            public void keyTyped(KeyEvent e) {
	                // TODO Auto-generated method stub
	                int charstr = e.getKeyChar();
	                String str = textNumber.getText();
	                if (str.length() == 0) {
	                    textNumber.setText(0 + "");
	                }

	                // control the value between 0 and 9
	                if (charstr < KeyEvent.VK_0 || charstr > KeyEvent.VK_9) {
	                    e.consume();
	                }
	                if (str.length() == 1) {
	                    if ("0".equals(str)) {
	                        textNumber.setText("");
	                    }
	                }
	                if (str.length() > 0) {
	                    if (str.length() > 1) {
	                        e.consume();
	                        textNumber.setText(99 + "");
	                        int sum = Integer.parseInt(textNumber.getText());
	                        long price = Long.parseLong(Unitprice.toString());
	                        // labTotalsum.setText(price*sum+"");
	                        Totalsum = new BigDecimal((price * sum));
	                    }
	                }
	            }

	            @Override
	            public void keyPressed(KeyEvent e) {
	            }

	            @Override
	            public void keyReleased(KeyEvent e) {
	            }
	        });
	        this.add(textNumber);



        if (MyIsif.getStyle().equals("水墨UI")){
            btnsurebuy = new ShoppingBuyBtn("skin/8100226/newbutton/B22.png", 1, UIUtils.COLOR_WHITE2, UIUtils.TEXT_HY16, "确认购买", 1, this);
            btnsurebuy.setBounds(263, 298, 99, 24);
        }else {
            btnsurebuy = new ShoppingBuyBtn("inkImg/hongmu/1/a2.png", 1, UIUtils.COLOR_YELLOW1, UIUtils.TEXT_HY16, "确认购买", 1, this);
            btnsurebuy.setBounds(263, 298, 99, 24);
        }
	        this.add(btnsurebuy);

	        // 存放物品的表格1~24
	        for (int i = 0; i < 24; i++) {
	            GoodsListLabel[i] = new JLabel();
	            shopMouslistens[i] = new ShopMouslisten(i, this);
	            GoodsListLabel[i].addMouseListener(shopMouslistens[i]);
	            GoodsListLabel[i].setBounds(47 + (i % 6) * 52 - i % 6, 35 + (i / 6) * 52, 48, 49);
	            this.add(GoodsListLabel[i]);
	        }

	        image.setImage(image.getImage().getScaledInstance(38, 20, Image.SCALE_DEFAULT));
    }

    private ImageIcon icon = new ImageIcon("inkImg/newbackground/B260.png");
    private ImageIcon icon2 = new ImageIcon("inkImg/hongmu/1/ss6666.png");
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (icon != null){
            if (MyIsif.getStyle().equals("水墨UI")){
                g.drawImage(icon.getImage(), 0, 0, 378, 398, this);
            }else {
                g.drawImage(icon2.getImage(), 0, 0, 378, 398, this);
            }

        }

        if (count == 1) {
            if (Balance!=null) {
                Util.drawPrice(g, Balance, 100, 362);
            }else if ("金钱".equals(Currency)) {
                Util.drawMoney(g, 100, 362);
            }else {
                Util.drawPrice(g, RoleData.getRoleData().getLoginResult().getSavegold(), 100, 362);
            }

        } else {
            if ("金钱".equals(Currency)) {
                Util.drawMoney(g, 100, 362);
            } else {
                Util.drawPrice(g, RoleData.getRoleData().getLoginResult().getCodecard(), 100, 362);
            }
        }
        Util.drawPrice(g, Unitprice, 100, 285);
        Util.drawPrice(g, Totalsum, 100, 336);
    }

    /**
     * 显示对应的商品图片
     * 
     * @return
     * @return
     */
    public void ShoppingsetIcon(int index) {
    		this.index = index;
            fysum();
            xz = -1;
            // 清空GoodsListLabel中所以的icon
            for (int i = 0; i < GoodsListLabel.length; i++) {
                GoodsListLabel[i].setIcon(null);
                GoodsListLabel[i].setBorder(null);
            }
            textNumber.setText(0 + "");// 数量
            Unitprice = new BigDecimal(0);// 单价
            Totalsum = new BigDecimal(0);// 总价
            shop = null;
            int size = shops.size() > (index + 1) * 24 ? 24 : shops.size() - index * 24;
            for (int i = 0; i < size; i++) {
                ImageIcon image = GoodsListFromServerUntil.imgpathAdaptive(shops.get(index * 24 + i).getShopskin(),49,49);
                GoodsListLabel[i].setIcon(image);
            }
    }

    /**刷新商品价格*/
    public void priceSX(String shopId,long price){
    	if (shop!=null&&shop.getShopid().equals(shopId)) {
    		shop.setShopprice(price);	
    		int TextNumber=Integer.parseInt(textNumber.getText());
    		Unitprice =new BigDecimal(price);// 单价
    		Totalsum  =new BigDecimal((price * TextNumber));// 改变总价
		}
    }
    /**选中商品*/
    public void xuanzhong(Shop yxshop, int shopPlace) {
    	if (shop != null && yxshop.getShopid() == shop.getShopid()) {
            // 如果这商品之前被点击则购买数量加1
            int TextNumber = Integer.parseInt(textNumber.getText()) + 1;// 数量
            if (TextNumber > 99) {
                return;
            }
            long LabUnitprice = shop.getShopprice();// 单价
            textNumber.setText(TextNumber + "");// 改变数量
            Totalsum = new BigDecimal((LabUnitprice * TextNumber));// 改变总价
        } else {
            if (shop != null) {
                GoodsListLabel[xz].setBorder(null);
            }
            xz = shopPlace;
            // 如果这商品没被点击则初始化购买数量 单价等数据
            shop = yxshop;
            textNumber.setText(1 + "");// 数量
            Unitprice = new BigDecimal(shop.getShopprice());// 单价
            Totalsum = new BigDecimal(shop.getShopprice());
        }
    	if (shop.getIsPrice()!=null) {//请求最新价格
    		String senmes = Agreement.getAgreement().ShopPriceAgreement("1|"+shop.getShopid());
            SendMessageUntil.toServer(senmes);
		}
    }

    /**
     * 初始化按钮个数
     */
    public void fysum() {
        int sum = (shops.size() - 1) / 24 + 1;
        if (pages == null) {
            pages = new ArrayList<>();
        }

        for (int i = 0; i < sum; i++) {
            if (i >= 8) {
                break;
            }
            if (i >= pages.size()) {
                if (sum > 8 && i == 0) {
                    pages.add(fyjlb("首页", i));
                } else if (sum > 8 && i == 7) {
                    pages.add(fyjlb("尾页", i));
                } else if (sum > 8) {
                    if (index == 0) {
                        pages.add(fyjlb(i + "", i));
                    } else if (index > sum - 5) {
                        int q = sum - 6;
                        pages.add(fyjlb((i + q) + "", i));
                    } else {
                        pages.add(fyjlb((i + index - 1) + "", i));
                    }
                } else {
                    pages.add(fyjlb((i + 1) + "", i));
                }
            } else {
                if (sum > 8 && i == 0) {
                    pages.get(i).setText("首页");
                } else if (sum > 8 && i == 7) {
                    pages.get(i).setText("尾页");
                } else if (sum > 8) {
                    if (index == 0) {
                        pages.get(i).setText(i + "");
                    } else if (index > sum - 5) {
                        int q = sum - 6;
                        pages.get(i).setText((i + q) + "");
                    } else {
                        pages.get(i).setText((i + index - 1) + "");
                    }
                } else {
                    pages.get(i).setText(i + 1 + "");
                }

            }
        }
        if (pages.size() > sum) {
            for (int i = pages.size() - 1; i >= sum; i--) {
                remove(pages.get(i));
                pages.remove(i);
            }
        }
    }

    private ImageIcon image = new ImageIcon("inkImg/hongmu/2/93_png.xy2uiimg.label_chat.png");

    /**
     * 初始化第i个按钮
     */
    public JLabel fyjlb(String text, int i) {
    		image = new ImageIcon("skin/8100226/button/B162.png");
    		JLabel lab = new JLabel();
            lab.setBounds(47 + i * 40, 242, 39, 23);
            lab.setIcon(image);
            lab.setBackground(new Color(0, 0, 0, 0));
            lab.setText(text);
            lab.setForeground(Color.WHITE);
            lab.setHorizontalTextPosition(SwingConstants.CENTER);
            lab.setFont(UIUtils.TEXT_FONT1);
            lab.addMouseListener(new ShopFyMouslisten(lab, this, null));
            this.add(lab);
            return lab;
    }

    /**
     * 画出预选边框
     * 
     * @return
     */
    public void PaintingText(int shopPlace) {
        GoodsListLabel[shopPlace].setBorder(BorderFactory.createLineBorder(Color.red));
    }

    /**
     * 清除预选边框
     * 
     * @return
     */
    public void ClearText(int shopPlace) {
        if (xz != shopPlace) {
            GoodsListLabel[shopPlace].setBorder(null);
        }
    }

    /**打开商店*/
    public void showshop(List<Shop> shops, String type, BigDecimal money) {
        this.shops = shops;
        this.count = 1;
        changeView();
        if (this.shops == null) {
            this.shops = new ArrayList<>();
        }
        ShoppingsetIcon(0);
        if ("45".equals(type)) {
            Currency = "师徒积分";
        } else if ("10".equals(type)) {
            Currency = "天庭积分";
        } else if ("61".equals(type)) {
            Currency = "帮战积分";
        } else if ("120".equals(type)) {
            Currency = "大雁塔积分";
        } else if ("121".equals(type)) {
            Currency = "地宫积分";
        } else if ("123".equals(type)) {
            Currency = "寻芳积分";
        } else if ("124".equals(type)) {
            Currency = "木魁积分";
        } else if ("126".equals(type)) {
            Currency = "水陆积分";
        } else if ("1106".equals(type)) {
            Currency = "种族赛积分";
        } else if ("500".equals(type)) {
            Currency = "幸运奖池积分";
        } else if ("515".equals(type)) {
            Currency = "擂台赛积分";
        } else if ("605".equals(type)) {
            Currency = "大闹天宫积分";
        } else if ("89".equals(type)) {
            Currency = "绑玉";
        } else if ("2027".equals(type)) {
            Currency = "竞技积分";
        }else if ("887".equals(type)) {
            Currency = "武神山积分";
        } else if ("2029".equals(type)) {
            Currency = "天梯积分";
        } else if (type.equals("3058")) {
            Currency = "魂值";
        }else {
            Currency = "金钱";
        }
        if (money != null) {
            Balance = money;
        } else if (!"金钱".equals(Currency)&&!"绑玉".equals(Currency)) {
            LoginResult loginResult = RoleData.getRoleData().getLoginResult();
            Balance = loginResult.getScoretype(Currency);
        }else {
        	Balance=null;
		}
    }

    /**
     * 获取商品数据 type表示类型 0:限购1:大闹天宫npc商店
     * 
     */
    public void getShopGoods(ShopGoodsBean shopGoodsBean) {
        if (shopGoodsBean.getType() == 0) {
            count = 0;
            goldType = 1;
            nId = shopGoodsBean.getnId();
            // 获取所有的商品
            shopList = shopGoodsBean.getShopList();
            // 默认获取仙玉的商品
            getShopGoodsType(shopList, 1);
            changeView();
            changeGoodsView();
        }
    }

    /**
     * 获取限购中对应的购买的商品
     * 
     * @param shopList
     * @param type
     */
    public void getShopGoodsType(List<Shop> shopList,int type) {
        if ("1".equals(type)) {
            Currency = "仙玉";
        } else {
            Currency = "金钱";
        }
        if (shops == null) {
            shops = new ArrayList<>();
        }
        shops.clear();
        for (int i = 0; i < shopList.size(); i++) {
            // 0是大话币 1仙玉
            if (shopList.get(i).getShoptype()==type) {
                shops.add(shopList.get(i));
            }
        }
        ShoppingsetIcon(0);
    }

    /**
     * 根据是否是限购来切换
     */
    public void changeView() {
    		if (count == 0) {
                getXianyuBtn().setVisible(true);
                getDahuabiBtn().setVisible(true);
                currencyLab.setIcon(CutButtonImage.getImage("inkImg/old/background/S125.png", 42, 14));
            } else {
                getXianyuBtn().setVisible(false);
                getDahuabiBtn().setVisible(false);
                currencyLab.setIcon(CutButtonImage.getImage("inkImg/old/background/S126.png", 42, 14));
            }
    }

    /**
     * 根据限购面板点击对应的仙玉或者
     */
    public void changeGoodsView() {
        try {
            if (goldType == 1) {
                xianyuBtn.setIcons(CutButtonImage.cuts("inkImg/hongmu/2/小选卡_仙玉_w63,h78.png"));
                dahuabiBtn.setIcons(CutButtonImage.cuts("inkImg/hongmu/2/小选卡_金币_未选中_w63,h78.png"));
                currencyLab.setIcon(CutButtonImage.getImage("inkImg/hongmu/2/仙玉W41,h13.png", 41, 13));
                getShopGoodsType(shopList, 1);
                Balance = RoleData.getRoleData().getLoginResult().getCodecard();
            } else {
                xianyuBtn.setIcons(CutButtonImage.cuts("inkImg/hongmu/2/小选卡_仙玉_未选中_w63,h78.png"));
                dahuabiBtn.setIcons(CutButtonImage.cuts("inkImg/hongmu/2/小选卡_金币_w63,h78.png"));
                currencyLab.setIcon(CutButtonImage.getImage("inkImg/hongmu/2/现金W41,h13.png", 41, 13));
                getShopGoodsType(shopList, 0);
                Balance = RoleData.getRoleData().getLoginResult().getGold();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public JTextField getTextNumber() {
        return textNumber;
    }

    public void setTextNumber(JTextField textNumber) {
        this.textNumber = textNumber;
    }

    public ShoppingBuyBtn getBtnsurebuy() {
        return btnsurebuy;
    }

    public void setBtnsurebuy(ShoppingBuyBtn btnsurebuy) {
        this.btnsurebuy = btnsurebuy;
    }

    public JLabel[] getGoodsListLabel() {
        return GoodsListLabel;
    }

    public void setGoodsListLabel(JLabel[] goodsListLabel) {
        GoodsListLabel = goodsListLabel;
    }

    public Shop getShop(int i) {
        if (index * 24 + i >= shops.size()) {
            return null;
        }
        return shops.get(index * 24 + i);
    }

    public List<Shop> getShops() {
        return shops;
    }

    public void setShops(List<Shop> shops) {
        this.shops = shops;
        ShoppingsetIcon(0);
    }

    public Shop getShop() {
        return shop;
    }

    public void setShop(Shop shop) {
        this.shop = shop;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public ShoppingBuyBtn getXianyuBtn() {
        if (xianyuBtn == null) {
            xianyuBtn = new ShoppingBuyBtn("inkImg/hongmu/2/小选卡_仙玉_w63,h78.png", 1, 2, this);
            xianyuBtn.setBounds(50, 15, 63, 26);
            xianyuBtn.setOpaque(false);
        }

        return xianyuBtn;
    }

    public void setXianyuBtn(ShoppingBuyBtn xianyuBtn) {
        this.xianyuBtn = xianyuBtn;
    }

    public ShoppingBuyBtn getDahuabiBtn() {
        if (dahuabiBtn == null) {
            dahuabiBtn = new ShoppingBuyBtn("inkImg/hongmu/2/小选卡_金币_未选中_w63,h78.png", 1, 3, this);
            dahuabiBtn.setBounds(50 + 65, 15, 63, 26);
            dahuabiBtn.setOpaque(false);
        }
        return dahuabiBtn;
    }

    public void setDahuabiBtn(ShoppingBuyBtn dahuabiBtn) {
        this.dahuabiBtn = dahuabiBtn;
    }

    public List<Shop> getShopList() {
        return shopList;
    }

    public void setShopList(List<Shop> shopList) {
        this.shopList = shopList;
    }

    public JLabel getCurrencyLab() {
        if (currencyLab == null) {
            currencyLab = new JLabel();
            currencyLab.setOpaque(false);
            	currencyLab.setBounds(50, 346 + 2, 42, 14);
                currencyLab.setIcon(CutButtonImage.getImage("inkImg/old/background/S126.png", 42, 14));
        }
        return currencyLab;
    }

    public void setCurrencyLab(JLabel currencyLab) {
        this.currencyLab = currencyLab;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public int getGoldType() {
        return goldType;
    }

    public void setGoldType(int goldType) {
        this.goldType = goldType;
    }

    public Integer getnId() {
        return nId;
    }

    public void setnId(Integer nId) {
        this.nId = nId;
    }

    public ImageIcon getIcon() {
        return icon;
    }

    public void setIcon(ImageIcon icon) {
        this.icon = icon;
    }
}
